export default {
  namespaced: true,
  state: () => ({
    // 每个商品的信息对象，都包含如下 6 个属性：
    // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
    cart: JSON.parse(uni.getStorageSync('cart') || '[]')
  }),
  
  mutations: {
    //没有该商品则将商品加到购物车，有该商品增加数量
    addToCart(state, goods) {
      const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
      // console.log(findResult);
      if(!findResult) {
        state.cart.push(goods)
      } else {
        findResult.goods_count++
      }
      this.commit('m_cart/saveToStorage')
    },
    saveToStorage(state) {
      uni.setStorageSync('cart',JSON.stringify(state.cart))
    },
    //修改商品状态
    updateGoodsState(state, goods) {
      const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
      if(findResult) {
        findResult.goods_state = goods.goods_state
      }
      this.commit('m_cart/saveToStorage')
    },
    // 修改购物车中商品数量
    updateGoodsCount(state, goods) {
      const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
      if(findResult) {
        findResult.goods_count = goods.goods_count
      }
      this.commit('m_cart/saveToStorage')
    },
    //根据id删除购物车中商品
    removeGoodsById(state, goods_id) {
      state.cart = state.cart.filter(x => x.goods_id !== goods_id)
      this.commit('m_cart/saveToStorage')
    },
    
    //全选功能
    updateAllGoodsState(state, newState) {
      state.cart.forEach(x => x.goods_state = newState)
      this.commit('m_cart/saveToStorage')
    }
  },
  
  actions: {},
  
  getters: {
    //购物车中所有商品的数量
    total(state) {
      // let sum = 0
      // state.cart.forEach(goods => sum += goods.goods_count)
      // return sum
     return state.cart.reduce((sum, goods) => sum += goods.goods_count, 0)
    },
    //结算区域计算被勾选的商品总数量
    checkedCount(state) {
      return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count, 0)
    },
    
    //计算购物车中被选中商品的总价格
    allCheckedGoodsPrice(state) {
     return state.cart.filter(x => x.goods_state)
     .reduce((totalPrice, item) => totalPrice += item.goods_count * item.goods_price, 0)
     .toFixed(2)
    }
  },
  
  }